package com.sx.core.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import static java.awt.Color.BLACK;
import static java.awt.Color.WHITE;

/**
 * Created by lihao on 16/4/28.
 */
public class QrUtils {
    static Log log= LogFactory.getLog(QrUtils.class);
    public static void encodeWechatQr(InputStream bg,String content,File file) throws Exception{
        try{
            int x=359, y=80, width=323, height=323;
            BufferedImage image= qr(content,width,height);
            BufferedImage image2= ImageIO.read(bg);
            Graphics g=image2.getGraphics();
            g.drawImage(image,x,y,width,height,null);
            ImageIO.write(image2,"jpg", file);
        }finally {
            bg.close();
        }


    }
    public static void main(String[] args) throws Exception{
//        encodeWechatQr(Thread.currentThread().getContextClassLoader().getResourceAsStream("bg.jpg"),"ddd",new File("/Users/lihao/Downloads/ttq.jpg"));


//        createQr("https://itunes.apple.com/us/app/bao-he/id1096015737?mt=8",200,200,new File("/Users/lihao/Downloads/ttq.jpg"));
//        createQr("http://www.scmc.edu.cn",360,360,new File("/Users/lihao/Downloads/chuanmei.jpg"));
        createQr("http://yx.scac.edu.cn:9004/mobile/app/download.html",360,360,new File("/Users/lihao/Downloads/jz.jpg"));
        createQrLogo("http://yx.scac.edu.cn:9004/mobile/app/download.html",360,360,new File("/Users/lihao/Downloads/jz1.jpg"),FileUtils.openInputStream(new File("/Users/lihao/Downloads/timg1.jpg")));
//        testDecode();
    }
    public static String readDecode(File file){
        String filePath = "/Users/lihao/Downloads/33E272250230CFA71DF5FAFC4772C646.jpg";
        BufferedImage image;
        try {
            image = ImageIO.read(file);
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            return result.getText();
//            JSONObject content = JSONObject.parseObject(result.getText());
//            System.out.println("图片中内容：  ");
//            System.out.println("author： " + content.getString("author"));
//            System.out.println("zxing：  " + content.getString("zxing"));
//            System.out.println("图片中格式：  ");
//            System.out.println("encode： " + result.getBarcodeFormat());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static BufferedImage qr(String content,int width,int height) throws Exception{
        Hashtable hints= new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    public static boolean createQr(String content,int width,int height,File outputFile){
        OutputStream outputStream=null;
        try{
            String format = "png";
            Hashtable hints= new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
            outputStream=FileUtils.openOutputStream(outputFile);
            MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
            return true;
        }catch (Exception e){
            log.error("createQr",e);
        }finally {
            IOUtils.closeQuietly(outputStream);
        }
        return false;
    }
    public static void downloadQr(String content,int width,int height,OutputStream outputStream){
        try{
            String format = "png";
            Hashtable hints= new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
            MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
        }catch (Exception e){
            log.error("downloadQr",e);
        }finally {
            IOUtils.closeQuietly(outputStream);
        }
    }

    public static boolean createQrLogo(String content,int width,int height,File outputFile,InputStream logoFile){
        String format = "png";
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        Image img=null;
        try{
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int bitMatrixWidth = bitMatrix.getWidth();
            int bitMatrixHeight = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(bitMatrixWidth, bitMatrixHeight, BufferedImage.TYPE_INT_RGB);

            for(int x=0;x<width;x++){
                for(int y=0;y<height;y++){
                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK.getRGB() : WHITE.getRGB());
                }
            }
            Graphics2D gs = image.createGraphics();
            //载入logo
            img = ImageIO.read(logoFile);
            int imgWidth= img.getWidth(null);
            int imgHeight= img.getHeight(null);

            gs.drawImage(img, (width-imgWidth)/2, (height-imgHeight)/2, null);
            gs.dispose();
            img.flush();
            return ImageIO.write(image, format, outputFile);
        }catch (Exception e){
            log.error("createQr",e);
        }finally {
            IOUtils.closeQuietly(logoFile);
        }
        return false;
    }
}
